package com.aaa.config;


import com.aaa.entity.Staff;
import com.aaa.service.FunctionService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

@Component
public class RbacConfig {
    //del     del?id=1 需要验证路径是否匹配辅助类 验证两个字符串相互匹配   匹配0或多个字符
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Resource
    private FunctionService functionService;
    /**
     * 访问路径与该角色拥有路径是否匹配
     *  匹配  返回true
     *  不匹配  返回false
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication){
        boolean isPermission = false;
        //1 获取当前的登陆用户的信息
        Object obj = authentication.getPrincipal();
        if(obj instanceof UserDetails){
            Staff userDetails= (Staff) obj;
            //2 根据用户信息查询数据得到拥有的菜单信息
            Set<String> urls=functionService.find(userDetails.getId());
           // System.out.println(urls);
            /*Set<String> urls = new HashSet<>();
//            urls.add("/roomtype/findAll");
            urls.add("/staff/*");
            urls.add("/function/*");*/
            //3 判断访问路径  与拥有菜单是否匹配
            for(String url : urls){
                System.out.println(url);
                if(antPathMatcher.match(url,request.getRequestURI())){
                    isPermission = true;
                    break;
                }
            }
        }
        //4 返回值
        return isPermission;
    }
}
